package main

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

const Type_StaticMethod = 0 // 调用静态方法
const Type_NewClass = 1     // 返回 new class 的 obj
const Type_ObjMethod = 2    // 调用 obj 的方法
const Type_ApisMethod = 3   // 调用Apis的方法

// WitSdk 参数
const witUid = ""
const witPid = ""
const witSecretId = ""
const witSecretKey = ""

// 提交的请求参数
type request struct {
	WitUid      string   `json:"witUid"`
	WitPid      string   `json:"witPid"`
	WitPluginId string   `json:"witPluginId"`
	Class       string   `json:"class"`
	Func        string   `json:"func"`
	Param       []string `json:"param"`
	Type        int      `json:"type"`
	Method      string   `json:"method"`
	T           int      `json:"t"`
	Sign        string   `json:"sign,omitempty"`
}

func main() {
	// 封装请求内容
	req := request{
		WitUid:      witUid,
		WitPid:      witPid,
		WitPluginId: "",
		Class:       "Lib\\Ws",
		Func:        "GetWsUrl",
		Param: []string{
			"ws_receive",
		},
		Type:   Type_StaticMethod,
		Method: "json",
	}
	req.T = int(time.Now().Unix())
	signStr, _ := json.Marshal(&req)
	req.Sign = getSign(signStr)
	reqBody, _ := json.Marshal(&req)
	rsp, err := http.Post("https://api.witframe.com/lib", "", strings.NewReader(string(reqBody)))
	if err != nil {
		panic(err)
	}

	// 获取回包内容
	defer rsp.Body.Close()
	rspBody, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(rspBody))
}

// getSign 计算签名
func getSign(s []byte) string {
	signStr := witSecretId + "|" + string(s)
	m := hmac.New(sha1.New, []byte(witSecretKey))
	m.Write([]byte(signStr))
	return hex.EncodeToString(m.Sum(nil))
}
